#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QIcon>
#include <QMessageBox>
#include <QByteArray>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSize>
#include <QListWidget>
#include <QListWidgetItem>
#include <QDateTime>
#include <QUrl>

#include "message.h"
#include "server.h"
#include "chatitem.h"
#include "frienditem.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint);

    m_addFriendsWidget = new AddFriendsWidget();
    connect(m_addFriendsWidget, &AddFriendsWidget::signal_friendRequest, this, &MainWindow::slot_receiveChatMessage);
    connect(m_addFriendsWidget, &AddFriendsWidget::signal_addFriendSuccess, this, &MainWindow::slot_agreeFriendRequestSuccess);

    connect(ui->pushButton_chat, &QPushButton::clicked, this, &MainWindow::slot_switchPage);
    connect(ui->pushButton_friend, &QPushButton::clicked, this, &MainWindow::slot_switchPage);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    for (auto iterator = m_chats.begin(); iterator != m_chats.end(); ++iterator) {
        iterator.value()->close();
    }
    m_addFriendsWidget->close();
    m_webSocketClient->close();
}

void MainWindow::slot_signInSuccess(QJsonObject loginResult)
{
    // 设置userId
    m_userId = loginResult.value("data").toString();
    qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "loginResult =" << QString(QJsonDocument(loginResult).toJson());
    qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "m_userId =" << m_userId;
    ui->label_userId->setText(m_userId);

    m_addFriendsWidget->setUserId(m_userId);

    // 设置用户名
    m_username = loginResult.value("username").toString();
    ui->label_username->setText(m_username);

    // 获取好友列表
    m_request.setUrl(QUrl("http://" + Server::serverAddr() + ":" + Server::port() + "/friends/" + m_userId));
    m_manager.get(m_request);
    connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slot_getFriendsReply(QNetworkReply *)));

    // 初始化服务器
    m_webSocketClient = new WebSocketClient;
    m_webSocketClient->connectUrl("ws://" + Server::serverAddr() + ":" + Server::port() +"/chat/" + m_userId);
    connect(m_webSocketClient, SIGNAL(signal_receiveTextMessage(Message)), this, SLOT(slot_receiveTextMessage(Message)));

    this->show();
}

void MainWindow::slot_getFriendsReply(QNetworkReply *reply) {
    if (reply->error()) {
        qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "Error!";
//        QMessageBox::warning(this, tr("登录失败"), tr("请检查网络连接"), QMessageBox::Ok);
    } else {
        // 解析reply中携带的Json
        QByteArray byteArray = reply->readAll();
        QJsonParseError jsonParseError;
        QJsonDocument parseDocument = QJsonDocument::fromJson(byteArray, &jsonParseError);
        if (jsonParseError.error == QJsonParseError::NoError) {
            if (parseDocument.isObject()) {
                QJsonObject resultJsonObject = parseDocument.object();
                if (resultJsonObject.contains("success")) {
                    bool isSuccess = resultJsonObject.value("success").toBool();
                    if (isSuccess) {
                        QJsonArray friendsJsonArray = resultJsonObject.value("data").toArray();
                        for (int i = 0; i < friendsJsonArray.count(); i++) {
                            qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "friend =" << QString(QJsonDocument(friendsJsonArray.at(i).toObject()).toJson());
                            addFriendItem(friendsJsonArray.at(i).toObject());
                        }
                    } else {

                    }
                }
            }
        }
    }

    reply->deleteLater();
}

void MainWindow::slot_receiveTextMessage(Message message)
{
    ChatWidget *chatWidget = nullptr;
    ChatItem *chatItem = nullptr;
    if (message.type() == Message::SINGAL_CHAT) {
        QString fromId = message.fromId();
        if (m_chats.contains(fromId) && m_chatItems.contains(fromId)) {
            chatWidget = m_chats.value(fromId);
            chatItem = m_chatItems.value(fromId);
        } else {
            chatItem = addChatItem(fromId, message.type(), m_userId);

            if (chatItem != nullptr) {
                chatWidget = chatItem->chatWidget();
            }
        }
    } else if (message.type() == Message::GROUP_CHAT) {
        QString groupId = message.groupId();
        if (m_chats.contains(groupId) && m_chatItems.contains(groupId)) {
            chatWidget = m_chats.value(groupId);
            chatItem = m_chatItems.value(groupId);
        } else {
            chatItem = addChatItem(groupId, message.type(), m_userId);

            if (chatItem != nullptr) {
                chatWidget = chatItem->chatWidget();
            }
        }
    } else if (message.type() == Message::FRIEND_REQUEST) {
        m_addFriendsWidget->slot_receiveFriendRequest(message);
        return;
    }

    qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << message.getMessage();

    chatWidget->slot_chatReceiveMessage(message);
    chatItem->setLatestMessage(message.data());
    chatItem->setTimestamp(message.timestamp());

//    qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "timestamp:" << message.timestamp().toString();

}

void MainWindow::slot_receiveChatMessage(Message message)
{
    message.setFromId(m_userId);
    ChatItem *chatItem = nullptr;
    if (message.type() == Message::SINGAL_CHAT) {
        chatItem = m_chatItems.value(message.toId());
    } else if (message.type() == Message::GROUP_CHAT) {
        chatItem = m_chatItems.value(message.groupId());
    }

    if (chatItem != nullptr) {
        chatItem->setLatestMessage(message.data());
        chatItem->setTimestamp(message.timestamp());
    }

//    qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << message.getMessage();
    m_webSocketClient->sendTextMessage(message.getMessage());
}

void MainWindow::slot_switchPage()
{
    QPushButton *pushButton = qobject_cast<QPushButton*>(sender());//得到按下的按钮的指针

    if (pushButton == ui->pushButton_chat) {
        ui->stackedWidget->setCurrentIndex(1);
    } else if (pushButton == ui->pushButton_friend) {
        ui->stackedWidget->setCurrentIndex(0);
    }
}

void MainWindow::slot_agreeFriendRequestSuccess(QJsonObject jsonObj)
{
//    Message message;
//    message.setType(Message::SINGAL_CHAT);
//    message.setFromId(m_userId);
//    message.setToId(jsonObj.value("id").toString());
//    message.setData("我同意了你的好友请求，开始聊天吧");

//    addChatItem(message.toId(), Message::SINGAL_CHAT);
//    slot_receiveChatMessage(message);
    addFriendItem(jsonObj);
}


void MainWindow::on_pushButton_addFriends_clicked()
{
    m_addFriendsWidget->show();
}

void MainWindow::initSystemTrayIcon()
{
    m_systemTrayIcon = new QSystemTrayIcon;
    m_systemTrayIcon->setIcon(QIcon(":/img/res/icon.png"));
    m_systemTrayIcon->setToolTip("Link");

    connect(m_systemTrayIcon, &QSystemTrayIcon::activated,
        [=](QSystemTrayIcon::ActivationReason reason) {
            switch(reason) {
            case QSystemTrayIcon::Trigger: // 单击托盘图标
                this->show();
                break;
            default:
                break;
        }
    });

    m_systemTrayIcon->show();
}

ChatItem *MainWindow::addChatItem(QString toId, Message::Type chatType, QString username)
{
    if (toId.isEmpty()) {
        return nullptr;
    }

    if (m_chats.contains(toId)) {
        m_chats.value(toId)->show();
        return nullptr;
    }

    ChatWidget *chatWidget = new ChatWidget;
    chatWidget->setChatType(chatType);
    chatWidget->setToId(toId);

    if (chatType == Message::SINGAL_CHAT) {
        chatWidget->setChatTitle(toId);
    } else if (chatType == Message::GROUP_CHAT) {
        chatWidget->setChatTitle("群聊 " + toId);
    }

    m_chats.insert(toId, chatWidget);
    connect(chatWidget, &ChatWidget::signal_chatSendMessage, this, &MainWindow::slot_receiveChatMessage);

    ChatItem *chatItem = new ChatItem(this);
    chatItem->setItemData(username, QDateTime::currentDateTime(), "");
    chatItem->setChatWidget(chatWidget);
    m_chatItems.insert(toId, chatItem);

    QListWidgetItem* listWidgetItem = new QListWidgetItem;
    ui->listWidget->insertItem(0, listWidgetItem);
    ui->listWidget->setItemWidget(listWidgetItem, chatItem);

    m_chats.value(toId)->show();
    return chatItem;
}

void MainWindow::addFriendItem(QJsonObject friendJsonObject)
{
    FriendItem *friendItem = new FriendItem(this);
    friendItem->setUserId(friendJsonObject.value("id").toString());
    friendItem->setUsername(friendJsonObject.value("username").toString());
    connect(friendItem, &FriendItem::signal_addChat, this, &MainWindow::addChatItem);

    QListWidgetItem* listWidgetItem = new QListWidgetItem;
    ui->listWidget_friends->insertItem(0, listWidgetItem);
    ui->listWidget_friends->setItemWidget(listWidgetItem, friendItem);
}

//void MainWindow::on_pushButton_startChat_clicked()
//{
//    QString toId = ui->lineEdit_toId->text();

//    if (toId.isEmpty()) {
//        QMessageBox::warning(this, "警告", "要接收消息的用户的用户id不能为空", QMessageBox::Ok);
//        return;
//    }

//    if (!m_chats.contains(toId)) {
//        m_chatItems.insert(toId , addChatItem(toId, Message::SINGAL_CHAT));
//    } else {
//        m_chats.value(toId)->show();
//    }

//    ui->lineEdit_toId->clear();
//}


void MainWindow::on_pushButton_groupChat_clicked()
{
    QString groupId = ui->lineEdit_groupId->text();

    if (groupId.isEmpty()) {
        QMessageBox::warning(this, "警告", "群聊ID不能不能为空", QMessageBox::Ok);
        return;
    }

    if (!m_chats.contains(groupId)) {
        m_chatItems.insert(groupId, addChatItem(groupId, Message::GROUP_CHAT, groupId));
        m_chats.value(groupId)->sendOnlineMessage(m_userId);
    } else {
        m_chats.value(groupId)->show();
    }
}


void MainWindow::on_pushButton_signOut_clicked()
{
    this->close();
    emit signal_signOut();
}

